<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{

    public function add()
    {
       if(!user_ins()->is_logged_in())
       return ['status'=>0 ,'msg'=>'login requeired'];
       if(!rq('content'))
       return ['status'=>0 ,'msg'=>'empt content'];
       if(!rq('question_id') && !rq('answer_id') ||
          rq('question_id') && rq('answer_id'))
       return ['status'=>0 ,'msg'=>'question_id or answer_id is requeired'];

      if(rq('question_id'))
       {
        $question = question_ins()->find(rq('question_id'));
        if (!$question)  return ['status'=>0 ,'msg'=>'question  is not exits'];
        $this->question_id = rq('question_id');

      }
      if (rq('answer_id'))
      {
        $answer = answer_ins()->find(rq('answer_id'));
        if (!$answer)  return ['status'=>0 ,'msg'=>'answer  is not exits'];
        $this->answer_id = rq('answer_id');
      }

     if (rq('id'))
     {
       $target = $this->find(rq('id'));

       if(!$target) return ['status'=>0 ,'msg'=>'target comment  is not exits'];
       if($target->user_id == session('user_id'))
       return ['status'=>0 ,'msg'=>'connot reply to myself'];
       $this->reply_to = rq('id');
     }

      $this->content = rq('content');
      $this->user_id = session('user_id');
      return $this->save() ?
      ['status' => 1 ,'msg'=>$this->id]:
      ['status' => 0 ,'msg'=>'db insert fauiled'];

    }

    public function read()
    {

      if(!rq('question_id') && !rq('answer_id') ||
         rq('question_id') && rq('answer_id'))
      return ['status'=>0 ,'msg'=>'question_id or answer_id is requeired'];

      if(rq('question_id')){
      $question = question_ins()->find(rq('question_id'));
      if (!$question ) ['status'=>0 ,'msg'=>'question  is not exits'];
      $data =$this->where('question_id',rq('question_id'))->get();

    }else {
      $answer= answer_ins()->find(rq('answer_id'));
      if (!$answer) ['status'=>0 ,'msg'=>'answer  is not exits'];
      $data =$this->where('answer_id',rq('answer_id'))->get();
    }

      return ['status'=>1, 'data' =>$data->keyBy('id')] ?:
            ['status' => 0 ,'msg'=>'db insert fauiled'];
    }

    public function remove()
    {
     if(!user_ins()->is_logged_in())
     return ['status'=>0 ,'msg'=>'login requeired'];
     if(!rq('id'))
      return ['status'=>0 ,'msg'=>'id is requeired'];

     $comment  = $this->find(rq('id'));
     if(!$comment)
     return ['status'=>0 ,'msg'=>'comment  is not exits'];

     if($comment->user_id != session('user_id'))
     return ['status'=>0 ,'msg'=>'permission denned'];


      return $comment->delete()?
      ['status'=>1 ] :
      ['status' => 0 ,'msg'=>'db delete fauiled'];


    }
}
